package com.yiwei.zxp.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.GoodsDetailEditAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.UploadImgBean;
import com.yiwei.zxp.api.model.UploadImgModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.GoodsDetailPhotoEvent;
import com.yiwei.zxp.util.ImageUtil;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.view.MyItemTouchHelper;
import com.yiwei.zxp.view.V19FrameLayout;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class GoodsDetailEditActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.layout_good_add)
    LinearLayout layoutGoodAdd;
    private Unbinder unbiner;
    private int REQUEST_CODE_CHOOSE = 100;
    private GoodsDetailEditAdapter adapter;
    private int upload_index = 0;
    private ArrayList<String> mSubmitImages = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail_edit);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("编辑商品详情");
        txtRight.setText("上传");
        txtRight.setVisibility(View.VISIBLE);

        adapter = new GoodsDetailEditAdapter(this);
        adapter.setOnChooseListener(new GoodsDetailEditAdapter.OnChooseListener() {
            @Override
            public void onClick() {
                txtRight.setText("完成");
            }
        });
        ItemTouchHelper.Callback callback = new MyItemTouchHelper(adapter);
        //实现Callback
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        //填充到myview  也就是RecyclerView
        helper.attachToRecyclerView(list);

        list.setAdapter(adapter);
        ArrayList<String> dataImage = getIntent().getStringArrayListExtra("data");
        if (dataImage != null && dataImage.size() != 0) {
            mSelectedImage = dataImage;
            adapter.add(mSelectedImage, false);
            btnSubmit.setSelected(true);
            layoutGoodAdd.setVisibility(View.GONE);
        }
    }

    public void getUploadImg(String img) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = img;
        Api.api_service.getUploadImg(bean).compose(RxLifeUtil.NoErrorOn(this)).
                doOnError(throwable -> {
                    loadingDialog.dismiss();
                    ToastUtil.makeText(this, "上传失败");
                }).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends UploadImgModel>>() {
            @Override
            public ObservableSource<? extends UploadImgModel> apply(Throwable throwable) throws Exception {
                throwable.printStackTrace();
                return Observable.empty();
            }
        }).subscribe(result -> {
            if (result.code.equals("00")) {
                mSubmitImages.add(result.datas.url);
                upload_index++;
                if (upload_index == adapter.getItemCount()) {
                    loadingDialog.dismiss();
                    EventBus.getDefault().post(new GoodsDetailPhotoEvent(mSubmitImages));
                    ToastUtil.makeText(this, "上传成功");
                    finish();
                    return;
                }
                while (adapter.getmSource().get(upload_index).startsWith("http")) {
                    mSubmitImages.add(adapter.getmSource().get(upload_index));
                    upload_index++;
                    if (upload_index == adapter.getItemCount()) {
                        loadingDialog.dismiss();
                        EventBus.getDefault().post(new GoodsDetailPhotoEvent(mSubmitImages));
                        ToastUtil.makeText(this, "上传成功");
                        finish();
                        return;
                    }
                }
                getUploadImg(ImageUtil.Bitmap2StrByBase64(ImageUtil.decodeUri(this, Uri.parse(adapter.getmSource().get(upload_index)), 1000, 1700), 100));
            } else {
                if (!TextUtils.isEmpty(result.msg)) {
                    ToastUtil.makeText(this, result.msg);
                }
                loadingDialog.dismiss();
            }

        });
    }


    List<Uri> mSelected;
    List<String> mSelectedImage = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            layoutGoodAdd.setVisibility(View.GONE);
            mSelected = Matisse.obtainResult(data);
            mSelectedImage.clear();
            for (int i = 0; i < mSelected.size(); i++) {
                mSelectedImage.add(mSelected.get(i).toString());
            }

            adapter.add(mSelectedImage, false);
            btnSubmit.setSelected(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.layout_good_add, R.id.btn_back, R.id.txt_right, R.id.btn_submit})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.layout_good_add:
            case R.id.txt_right:
                if (UI.toString(txtRight).equals("上传")) {
                    if (adapter.getItemCount() >= 15) {
                        ToastUtil.makeText(this, "最多上传15张图片");
                        return;
                    }
                    int maxUpload = 15 - adapter.getItemCount();
                    Matisse.from(this)
                            .choose(MimeType.allOf())
                            .countable(true)
                            .maxSelectable(maxUpload)
                            .theme(R.style.Matisse_Zhihu)//主题  暗色主题 R.style.Matisse_Dracula
//                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE);
                } else if (UI.toString(txtRight).equals("完成")) {
                    adapter.setClearOperator();
                    txtRight.setText("上传");
                }
                break;
            case R.id.btn_submit:
                if (adapter.getItemCount() == 0) {
                    ToastUtil.makeText(this, "当前图片列表为空");
                    return;
                }
                mSubmitImages.clear();
                upload_index = 0;

                while (adapter.getmSource().get(upload_index).startsWith("http")) {
                    mSubmitImages.add(adapter.getmSource().get(upload_index));
                    upload_index++;
                    if (upload_index == adapter.getItemCount()) {
                        EventBus.getDefault().post(new GoodsDetailPhotoEvent(mSubmitImages));
                        ToastUtil.makeText(this, "上传成功");
                        finish();
                        return;
                    }
                }
                getUploadImg(ImageUtil.Bitmap2StrByBase64(ImageUtil.decodeUri(this, Uri.parse(adapter.getmSource().get(upload_index)), 1000, 1700), 100));


                break;
        }
    }
}
